//
//  TestDecodable.swift
//  TestSwift
//
//  Created by 小星星吃KFC on 2021/6/5.
//

import Foundation


func TestDecodable() {
    
    struct User: Codable  {
        
        /// 可能未出现字段 用可选 ,或者用 let
        //        var id: Int = 0
        //        var title: String = ""
        //        var commentEnabled: Bool = true
        
        var id: Int
        var title: String
        var commentEnabled: Bool?
        
        var name: String? = "jim"
        //        let name: String?
        /// json 是时间戳,这里可以直接用date接收,这个不行,有误差
        let expiresIn: Date?
        var userName: String? = "tom"
    }
    
    //    let map:[String : Any] = ["id": 12345, "title": "My First Video"]
    //    let json = #"{"id": 12345, "title": "My First Video", "state": "reserved"}"#
    let json =
        """
    {"id": 12345,
    "title": "My First Video",
    "state": "reserved",
    "expiresIn":86400,
    "user_name":"tom"
    
    }
    """
    print("json=\(json)")
    
    let data = json.data(using:.utf8)!;
    
    let decode = JSONDecoder()
    /// 大小写 转驼峰
    decode.keyDecodingStrategy = .convertFromSnakeCase
    
    let user :User?  = try? decode.decode(User.self, from:data)
    
    
    print("user=\(String(describing: user))")
    print("user id=\(String(describing: user?.id))")
    print("user userName=\(String(describing: user?.userName))")
    print("user expiresIn=\(String(describing: user?.expiresIn))")
    
    
    do {
        
        let json =
            """
            [
                {
                    "userName": "小名",
                    "age": 18,
                    "height": 178.56,
                    "sex": true
                },
                {
                    "userName": "小方",
                    "age": 18,
                    "height": 162.56,
                    "sex": false
                }
            ]
        """
        struct UserInfo: Codable {
            
            let userName: String
            let age: Int
            let height: Float
            let sex: Bool
        }
        
        let data = json.data(using:.utf8)!;
        let user :[UserInfo]?  = try? JSONDecoder().decode([UserInfo].self, from:data)
        
        
        print("UserInfo=\(String(describing: user))")
        
    }
    
}
